<template>
  <div class="spaces-container">
    <!-- 头部工具栏 -->
    <div class="header-toolbar">
      <div class="left-section">
        <el-breadcrumb separator=">">
          <el-breadcrumb-item @click="$router.push('/knowledge')">知识管理</el-breadcrumb-item>
          <el-breadcrumb-item>空间管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="right-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索空间名称或描述"
          prefix-icon="Search"
          class="search-input"
          @input="handleSearch"
          clearable
        />
        <el-button type="primary" @click="showCreateSpaceDialog = true">
          <el-icon><Plus /></el-icon>
          新建空间
        </el-button>
        <UserProfile />
      </div>
    </div>

    <!-- 筛选和视图控制 -->
    <div class="filter-toolbar">
      <div class="filter-section">
        <el-button-group>
          <el-button 
            :type="activeFilter === 'all' ? 'primary' : ''"
            @click="setActiveFilter('all')"
          >
            全部空间 ({{ totalSpaces }})
          </el-button>
          <el-button 
            :type="activeFilter === 'personal' ? 'primary' : ''"
            @click="setActiveFilter('personal')"
          >
            个人空间
          </el-button>
          <el-button 
            :type="activeFilter === 'team' ? 'primary' : ''"
            @click="setActiveFilter('team')"
          >
            团队空间
          </el-button>
        </el-button-group>
      </div>
      <div class="view-controls">
        <el-button-group>
          <el-button 
            :type="viewMode === 'grid' ? 'primary' : ''"
            @click="viewMode = 'grid'"
          >
            <el-icon><Grid /></el-icon>
          </el-button>
          <el-button 
            :type="viewMode === 'list' ? 'primary' : ''"
            @click="viewMode = 'list'"
          >
            <el-icon><List /></el-icon>
          </el-button>
        </el-button-group>
        <el-dropdown>
          <el-button>
            排序 <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="setSortBy('name')">按名称</el-dropdown-item>
              <el-dropdown-item @click="setSortBy('updated')">按更新时间</el-dropdown-item>
              <el-dropdown-item @click="setSortBy('created')">按创建时间</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'" class="spaces-grid">
        <SpaceList 
          :spaces="filteredSpaces"
          :view-mode="viewMode"
          @enter-space="enterSpace"
          @edit-space="editSpace"
          @delete-space="deleteSpace"
        />
      </div>

      <!-- 列表视图 -->
      <div v-if="viewMode === 'list'" class="spaces-table">
        <SpaceList 
          :spaces="filteredSpaces"
          :view-mode="viewMode"
          @enter-space="enterSpace"
          @edit-space="editSpace"
          @delete-space="deleteSpace"
        />
      </div>

      <!-- 空状态 -->
      <div v-if="filteredSpaces.length === 0" class="empty-state">
        <div class="empty-illustration">
          <el-icon size="80"><Collection /></el-icon>
        </div>
        <h3>{{ getEmptyStateTitle() }}</h3>
        <p>{{ getEmptyStateDescription() }}</p>
        <el-button type="primary" @click="showCreateSpaceDialog = true">
          <el-icon><Plus /></el-icon>
          创建第一个空间
        </el-button>
      </div>
    </div>

    <!-- 创建空间对话框 -->
    <el-dialog v-model="showCreateSpaceDialog" title="新建空间" width="500px">
      <el-form :model="newSpace" :rules="spaceRules" ref="spaceFormRef" label-width="80px">
        <el-form-item label="空间名称" prop="name">
          <el-input v-model="newSpace.name" placeholder="请输入空间名称" />
        </el-form-item>
        <el-form-item label="标识" prop="identifier">
          <el-input v-model="newSpace.identifier" placeholder="请输入空间标识（可选）" />
        </el-form-item>
        <el-form-item label="可见范围" prop="scopeType">
          <el-select v-model="newSpace.scopeType" placeholder="请选择可见范围" style="width: 100%">
            <el-option label="团队可见" value="user_group" />
            <el-option label="用户可见" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="可见性" prop="visibility">
          <el-select v-model="newSpace.visibility" placeholder="请选择可见性" style="width: 100%">
            <el-option label="私有" value="private" />
            <el-option label="公开" value="public" />
          </el-select>
        </el-form-item>
        <el-form-item label="主题色">
          <el-color-picker v-model="newSpace.color" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input 
            v-model="newSpace.description" 
            type="textarea" 
            placeholder="请输入空间描述（可选）"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateSpaceDialog = false">取消</el-button>
        <el-button type="primary" @click="createSpace" :loading="creating">创建</el-button>
      </template>
    </el-dialog>

    <!-- 编辑空间对话框 -->
    <el-dialog v-model="showEditSpaceDialog" title="编辑空间" width="500px">
      <el-form :model="editingSpace" :rules="spaceRules" ref="editSpaceFormRef" label-width="80px">
        <el-form-item label="空间名称" prop="name">
          <el-input v-model="editingSpace.name" placeholder="请输入空间名称" />
        </el-form-item>
        <el-form-item label="标识" prop="identifier">
          <el-input v-model="editingSpace.identifier" placeholder="请输入空间标识（可选）" />
        </el-form-item>
        <el-form-item label="可见范围" prop="scopeType">
          <el-select v-model="editingSpace.scopeType" placeholder="请选择可见范围" style="width: 100%">
            <el-option label="团队可见" value="user_group" />
            <el-option label="用户可见" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="可见性" prop="visibility">
          <el-select v-model="editingSpace.visibility" placeholder="请选择可见性" style="width: 100%">
            <el-option label="私有" value="private" />
            <el-option label="公开" value="public" />
          </el-select>
        </el-form-item>
        <el-form-item label="主题色">
          <el-color-picker v-model="editingSpace.color" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input 
            v-model="editingSpace.description" 
            type="textarea" 
            placeholder="请输入空间描述（可选）"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditSpaceDialog = false">取消</el-button>
        <el-button type="primary" @click="updateSpace" :loading="updating">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Grid, List, ArrowDown, Collection
} from '@element-plus/icons-vue'
import SpaceList from '@/components/knowledge/SpaceList.vue'
import UserProfile from '@/components/knowledge/UserProfile.vue'
import request from '@/utils/request'

const router = useRouter()
const route = useRoute()

// 响应式数据
const searchQuery = ref('')
const activeFilter = ref('all')
const viewMode = ref('grid')
const sortBy = ref('updated')
const showCreateSpaceDialog = ref(false)
const showEditSpaceDialog = ref(false)
const creating = ref(false)
const updating = ref(false)

const spaces = ref([])
const loading = ref(false)

const spaceFormRef = ref()
const editSpaceFormRef = ref()

const newSpace = reactive({
  name: '',
  identifier: '',
  scopeType: 'user_group',
  visibility: 'private',
  color: '#409EFF',
  description: ''
})

const editingSpace = reactive({
  id: '',
  name: '',
  identifier: '',
  scopeType: 'user_group',
  visibility: 'private',
  color: '#409EFF',
  description: ''
})

// 表单验证规则
const spaceRules = {
  name: [
    { required: true, message: '请输入空间名称', trigger: 'blur' },
    { min: 1, max: 50, message: '空间名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  scopeType: [
    { required: true, message: '请选择可见范围', trigger: 'change' }
  ],
  visibility: [
    { required: true, message: '请选择可见性', trigger: 'change' }
  ]
}

// 计算属性
const totalSpaces = computed(() => spaces.value.length)

const filteredSpaces = computed(() => {
  let filtered = spaces.value
  
  // 根据筛选条件过滤
  if (activeFilter.value === 'personal') {
    filtered = filtered.filter(space => space.scopeType === 'user')
  } else if (activeFilter.value === 'team') {
    filtered = filtered.filter(space => space.scopeType === 'user_group')
  }
  
  // 根据搜索关键词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(space => 
      space.name.toLowerCase().includes(query) ||
      (space.description && space.description.toLowerCase().includes(query)) ||
      (space.identifier && space.identifier.toLowerCase().includes(query))
    )
  }
  
  // 排序
  filtered.sort((a, b) => {
    if (sortBy.value === 'name') {
      return a.name.localeCompare(b.name)
    } else if (sortBy.value === 'updated') {
      return (b.updatedAt || 0) - (a.updatedAt || 0)
    } else if (sortBy.value === 'created') {
      return (b.createdAt || 0) - (a.createdAt || 0)
    }
    return 0
  })
  
  return filtered
})

// 方法
const setActiveFilter = (filter) => {
  activeFilter.value = filter
}

const setSortBy = (sort) => {
  sortBy.value = sort
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中实现
}

const getEmptyStateTitle = () => {
  if (searchQuery.value) {
    return '未找到匹配的空间'
  }
  if (activeFilter.value === 'personal') {
    return '暂无个人空间'
  }
  if (activeFilter.value === 'team') {
    return '暂无团队空间'
  }
  return '暂无知识空间'
}

const getEmptyStateDescription = () => {
  if (searchQuery.value) {
    return '尝试使用不同的关键词搜索，或者创建一个新的空间'
  }
  return '创建您的第一个知识空间，开始整理和分享知识'
}

const loadSpaces = async () => {
  loading.value = true
  try {
    // 获取当前用户信息（这里假设从localStorage或其他地方获取）
    const currentUser = localStorage.getItem('currentUser') || ''
    
    const response = await request.get('/api/spaces/accessible', {
      params: {
        username: currentUser
      }
    })
    if (response.data.code === '200') {
      spaces.value = response.data.data || []
    } else {
      ElMessage.error(response.data.msg || '加载空间失败')
    }
  } catch (error) {
    console.error('加载空间失败:', error)
    ElMessage.error('加载空间失败')
  } finally {
    loading.value = false
  }
}

const createSpace = async () => {
  if (!spaceFormRef.value) return
  
  try {
    const valid = await spaceFormRef.value.validate()
    if (!valid) return
  } catch {
    return
  }
  
  creating.value = true
  try {
    // 获取当前用户信息
    const currentUser = localStorage.getItem('currentUser') || ''
    
    const spaceData = {
      ...newSpace,
      createdBy: {
        id: '1',
        username: currentUser
      },
      updatedBy: {
        id: '1',
        username: currentUser
      }
    }
    
    const response = await request.post('/api/spaces', spaceData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.code === '200') {
      ElMessage.success('创建成功')
      showCreateSpaceDialog.value = false
      resetNewSpace()
      loadSpaces()
    } else {
      ElMessage.error(response.data.msg || '创建失败')
    }
  } catch (error) {
    console.error('创建空间失败:', error)
    ElMessage.error('创建空间失败')
  } finally {
    creating.value = false
  }
}

const resetNewSpace = () => {
  Object.assign(newSpace, {
    name: '',
    identifier: '',
    scopeType: 'user_group',
    visibility: 'private',
    color: '#409EFF',
    description: ''
  })
  if (spaceFormRef.value) {
    spaceFormRef.value.resetFields()
  }
}

const enterSpace = (space) => {
  router.push(`/knowledge/spaces/${space.id}`)
}

const editSpace = (space) => {
  Object.assign(editingSpace, {
    id: space.id,
    name: space.name,
    identifier: space.identifier || '',
    scopeType: space.scopeType,
    visibility: space.visibility,
    color: space.color || '#409EFF',
    description: space.description || ''
  })
  showEditSpaceDialog.value = true
}

const updateSpace = async () => {
  if (!editSpaceFormRef.value) return
  
  try {
    const valid = await editSpaceFormRef.value.validate()
    if (!valid) return
  } catch {
    return
  }
  
  updating.value = true
  try {
    // 获取当前用户信息
    const currentUser = localStorage.getItem('currentUser') || ''
    
    const spaceData = {
      ...editingSpace,
      updatedBy: {
        id: '1',
        username: currentUser
      }
    }
    
    const response = await request.put(`/api/spaces/${editingSpace.id}`, spaceData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.code === '200') {
      ElMessage.success('更新成功')
      showEditSpaceDialog.value = false
      loadSpaces()
    } else {
      ElMessage.error(response.data.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新空间失败:', error)
    ElMessage.error('更新空间失败')
  } finally {
    updating.value = false
  }
}

const deleteSpace = async (spaceId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个空间吗？删除后无法恢复。', '确认删除', {
      type: 'warning',
      confirmButtonText: '确定删除',
      cancelButtonText: '取消'
    })
    
    const response = await request.delete(`/api/spaces/${spaceId}`)
    if (response.data.code === '200') {
      ElMessage.success('删除成功')
      loadSpaces()
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除空间失败:', error)
      ElMessage.error('删除空间失败')
    }
  }
}

// 监听路由查询参数
watch(() => route.query.search, (newSearch) => {
  if (newSearch) {
    searchQuery.value = newSearch
  }
}, { immediate: true })

// 生命周期
onMounted(() => {
  loadSpaces()
})
</script>

<style scoped>
.spaces-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
}

.left-section {
  display: flex;
  align-items: center;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 300px;
}

.filter-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.view-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.main-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.spaces-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.spaces-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 8px;
}

.empty-illustration {
  margin-bottom: 24px;
  color: #ccc;
}

.empty-state h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 20px;
}

.empty-state p {
  color: #666;
  margin: 0 0 24px 0;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .filter-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .search-input {
    width: 100%;
  }
  
  .spaces-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .main-content {
    padding: 16px;
  }
  
  .right-section {
    flex-direction: column;
    gap: 8px;
  }
}
</style>